import axios from 'axios'
import router from '@/router'
import { clearLoginInfo } from '@/utils'
import {getToken} from '../utils/auth.js'
import { ElMessage } from 'element-plus'

const http = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 1000 * 30,
    withCredentials: true,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  let token = getToken()
  if(token) config.headers['token'] = token
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  let whiteList = ["application/msexcel"]
  if (response.data && response.data.code === 401) { // 401, token失效
    clearLoginInfo()
    router.push({ name: 'login' })
  } else if(response.data && (response.data.code === 200 ||response.data.code === 0 || Array.isArray(response.data))){
    return response.data
  } else {
    if(whiteList.includes(response.headers['content-type'])) {return response.data}
    ElMessage.error(response.data.msg)
    return Promise.reject(response.data)
  }
}, error => {
  ElMessage.error(error.msg)
  return Promise.reject(error)
})


export default http